package com.yz.smartpos.yztester.ui;

import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;

import com.yz.smartpos.yztester.R;
import com.yz.smartpos.yztester.util.TesterConfig;
import com.yz.smartpos.yztester.util.TesterState;
import com.yz.smartpos.yztester.util.Utils;
import com.yz.smartpos.yztester.util.YzTestRunner;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.yz.smartpos.yztester.util.FTPClientUtils;
/**
 */

public class ResultFragment extends Fragment {
    private static TextView title, showResult;
    private static Button clear;
    private static Button retest;
    private static Button uploadLog;
    private static Button stop;

    private static ScrollView scrollView;
    private static Handler uiHandler;
    private static String TAG = "ResultFra";
    private  int linCountMax = 1000;
    private float pressDownY = 0;
    public static int stop_flag = 0;
    public static ResultFragment newInstance() {
        ResultFragment fragment = new ResultFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }
    public ResultFragment() {
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        Log.i(TAG, "onCreateView");
        View view = inflater.inflate(R.layout.fragment_result, container, false);
        uiHandler = new UIHandler();
        title = (TextView) view.findViewById(R.id.title);
        showResult = (TextView) view.findViewById(R.id.show_result);
        showResult.setMovementMethod(ScrollingMovementMethod.getInstance());
        showResult.setGravity(Gravity.BOTTOM);
        showResult.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action =  event.getAction();
                if (action ==MotionEvent.ACTION_DOWN){
                    pressDownY =event.getY();
                }else if (action == MotionEvent.ACTION_UP){
                    float moveY = (event.getY() -pressDownY);
                    if ( moveY <=-100 || moveY >=100){
                        showResult.setGravity(8388659);
                    }
                }
                return false;
            }
        });

        clear = (Button) view.findViewById(R.id.clear);
        clear.setOnClickListener(v -> clearLog());

        retest = (Button) view.findViewById(R.id.retry);
        retest.setOnClickListener(new View.OnClickListener () {
            @Override
            public void onClick(View v) {
                Log.i("Button3","通过当前activity来实现按钮点击监听");
                if(TesterState.getRunState() == TesterState.TEST_RUNNING){
                    Utils.showToast("Testing", Toast.LENGTH_LONG);
                    Log.i(TAG, "Testing...");
                }
                else if(TesterState.mCurrentCase != null){
                    TesterState.setRunState(TesterState.TEST_RUNNING);
                    YzTestRunner mYzTestRunner = new YzTestRunner(TesterState.mCurrentCase);
                    Thread t = new Thread(mYzTestRunner);
                    t.start();
                }else {
                    Log.i("Button3","mCurrentCase:" + TesterState.mCurrentCase);
                }
            }
        });

        stop = (Button) view.findViewById(R.id.stop);
        stop.setOnClickListener(new View.OnClickListener () {
            @Override
            public void onClick(View v) {
                Log.i("Button4","stop button pressed");
                stop_flag = 1;
            };
        });

        uploadLog = (Button) view.findViewById(R.id.uploadLog);
        uploadLog.setOnClickListener(new View.OnClickListener () {
            @Override
            public void onClick(View v) {
                Log.i("Button4","upload log button pressed");

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try{
                            FTPClientUtils ftpclient = new FTPClientUtils();
                            boolean res = ftpclient.ftpConnect("192.168.15.10", "user1", "yz123456", 21);
                            Log.i("Button4","ftpConnect = " + res);
                            if(res == true) {
                                ftpclient.ftpChangePath("/test/log_api/");
                                String path_tmp = "/sdcard/Android/data/com.yz.smartpos.palmPayTester/files/Results/";
                                res = ftpclient.ftpUpload(path_tmp + "case_runned.txt", "case_runned.txt");
                                Log.i("Button4","ftpUpload case_runned.txt " + res);
                                Utils.showToast("Upload case_runned.txt " + res, Toast.LENGTH_LONG);

                                res = ftpclient.ftpUpload(path_tmp + "test.log", "test.log");
                                Log.i("Button4","ftpUpload test.log " + res);
                                Utils.showToast("Upload test.log " + res, Toast.LENGTH_LONG);

                                res = ftpclient.ftpUpload(path_tmp + "test_pm.log", "test_pm.log");
                                Log.i("Button4","ftpUpload test_pm.log " + res);
                                Utils.showToast("Upload test_pm.log " + res, Toast.LENGTH_LONG);

                                Utils.showToast("Upload OK!", Toast.LENGTH_LONG);
                                Log.i(TAG, "Upload OK!");
                            }
                        }catch (Exception e) {
                            Utils.showToast("Upload fail, Pls check network!", Toast.LENGTH_LONG);
                            Log.i(TAG, "Upload fail, Pls check network!");
                        }
                    }
                }).start();
            }
        });
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.i(TAG, "onResume");
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.i(TAG, "onPause");
    }

    public void appendLog_inner(String result) {
        uiHandler.obtainMessage(0, result).sendToTarget();
    }

    public void appendLog(String result) {
        uiHandler.obtainMessage(3, result).sendToTarget();
    }

    public synchronized void setLog(String result){
        uiHandler.obtainMessage(4, result).sendToTarget();

    }

    public void showTitle(String title) {
        uiHandler.obtainMessage(1, title).sendToTarget();
    }
    public void clearLog() {
        uiHandler.obtainMessage(2, "").sendToTarget();
    }
    public void scrollToBottom() {
        uiHandler.obtainMessage(5, "").sendToTarget();
    }

    class UIHandler extends Handler {

        private final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:SSS", Locale.getDefault());

        @Override
        public void dispatchMessage(Message msg) {
            super.dispatchMessage(msg);
            String str_tmp;

            switch (msg.what) {
                case 0:
                    str_tmp ="[" + sdf.format(new Date()) + "] " + msg.obj + "\n";
                    showResult.append(str_tmp);
                    try {
                        TesterConfig.result_log_out.append(str_tmp);
                        TesterConfig.result_log_out.flush();
                    }catch(IOException e){
                        Log.e(TAG, e.getMessage());
                    }
                    break;
                case 1:
                    title.setText((String) msg.obj);
                    break;
                case 2:
                    showResult.setText("");
                    break;
                case 3:
                    str_tmp = msg.obj + "\n";
                    if(showResult.getLineCount()>linCountMax)
                        showResult.setText("");
                    showResult.append(str_tmp);
//                    scrollView.getViewTreeObserver().addOnGlobalLayoutListener(() -> scrollView.post(() -> scrollView.fullScroll(View.FOCUS_DOWN)));
                    try {
                        TesterConfig.result_log_out.append(str_tmp);
                        TesterConfig.result_log_out.flush();
                    }catch(IOException e){
                        Log.e(TAG, e.getMessage());
                    }
                    break;
                case 4:
                    if(showResult!=null){
                        if ("".endsWith((String) msg.obj)){
                            showResult.setGravity(Gravity.BOTTOM);
                        }
                        showResult.setText(msg.obj + "\n");
                    }
                    break;
                case 5:
                    int offset = showResult.getLineCount() * showResult.getLineHeight();
                    if (offset > showResult.getHeight()) {
                        showResult.scrollTo( 0, offset - showResult.getHeight() );
                    }
                    break;
            }
        }
    }
}
